<template>
  <div class="main_container">
    <div
      v-for="(item, index) in blockList"
      :key="index"
      class="block"
      :style="{
          width: item.ownWidth? item.ownWidth + 'px' : singleWidth + 'px',
          height: item.ownHeight ? item.ownHeight + 'px' : singleHeight + 'px',
          position: 'absolute',
          left: item.x + 'px',
          top: item.y + 'px',
      }"
    >
      <div>
        <div v-if="index === 1" @click="changeBuju">哈哈</div>
        <div v-if="index === 2" @click="changeBuju2">哈哈</div>
        <component :is="handleComponents(item.num)"></component>
      </div>
    </div>
  </div>
</template>

<script>
// import commonHeader from '@/components/common_header'
import haha from './zhangyuhuiSecond'
import $ from 'jquery'
import _ from 'lodash'
import request from '@/assets/utils/request'

const findScreenJson = () => {
  return request({
    url: '/parkinglot/TestController/findScreenJson',
    method: 'post'
  })
}

const changeScreenJson = params => {
  return request({
    url: '/parkinglot/TestController/changeScreenJson',
    method: 'post',
    params
  })
}

const initPages = vm => {
  vm.singleWidth = $(window).width() / vm.columns
  vm.singleHeight = $(window).height() / vm.rows
  let arr = []
  for (let i = 0; i < vm.rows; i++) {
    for (let k = 0; k < vm.columns; k++) {
      arr.push({
        x: k * vm.singleWidth,
        y: i * vm.singleHeight,
        num: String(k + i * vm.columns)
      })
    }
  }
  vm.initalLayOut = arr
  // vm.blockList = _.cloneDeep(arr)
}

const _initPage = _.debounce(initPages, 500)

export default {
  components: {
    haha
  },
  data() {
    return {
      title: '智能物业管理系统',

      blockList: [
        {
          id: 7,
          name: 'haha'
        }
      ],
      initalLayOut: [], // 排版，页面布局对象
      dataList: [], // 数据对象，真实的数据对象有initlayout对象衍生出来

      rows: 3,
      columns: 5,

      singleWidth: '',
      singleHeight: ''
    }
  },

  computed: {
    blockLength() {
      return this.rows * this.columns
    }
  },

  watch: {
    initalLayOut: {
      handler() {
        this.setBlockList()
      },
      deep: true
    }
  },

  created() {
    // 初始化的时候不能使用_initPages,否则无法拿到this.singleWidth!!
    initPages(this)
    // this.initWebSocket()
  },

  mounted() {
    window.onresize = () => {
      _initPage(this)
    }
    changeScreenJson({
      jsonNum: 1
    })
      .then(() => {
        return findScreenJson()
      })
      .then(res => {
        this.initData = res.screenJsonObject
        this.setBlockList()
      })
  },

  methods: {
    setBlockList() {
      const obj = _.groupBy(this.initData, value => {
        return value.flag
      })
      const blockListObj = _.mapValues(obj, (value, key) => {
        if (key !== '-1') {
          return this.getCombinedBlockObj(value)
        } else {
          return this.getSingleBlockObj(value)
        }
      })
      const dataArr = _.flatten(_.values(blockListObj))
      this.blockList = this.combineDataLayOut(dataArr, this.initalLayOut)
    },

    combineDataLayOut(dataArr, layArr) {
      let finialList = []
      for (let i = 0; i < dataArr.length; i++) {
        for (let k = 0; k < layArr.length; k++) {
          if (layArr[k].num === dataArr[i].num) {
            finialList.push({
              ...dataArr[i],
              x: layArr[k].x,
              y: layArr[k].y
            })
          }
        }
      }
      return finialList
    },

    getCombinedBlockObj(value) {
      const { component, coordinatesX, coordinatesY } = value[0]
      return {
        component: component,
        num: _.sortBy(value, ['num'])[0].num,
        ownWidth: coordinatesX * this.singleWidth,
        ownHeight: coordinatesY * this.singleHeight
      }
    },

    getSingleBlockObj(value) {
      return value.map(item => {
        return {
          ..._.pick(item, ['component', 'num'])
        }
      })
    },

    handleComponents(num) {
      // const o = this.blockList.find(v => v.num === num)
      // return o ? o.component : ''
      return 'haha'
    },

    initWebSocket() {
      const ws = new WebSocket('WS://192.168.200.250:9000/FaceWebSocket/963')
      ws.onmessage = event => {
        let data = JSON.parse(event.data)
        console.log(data)
        this.initData = data
        this.setBlockList()
        // $('#content').after('<div>' + data +'</div>')
      }
      ws.onclose = () => {
        console.log('websocket连接已关闭')
      }
      ws.onerror = () => {
        console.log('websocket连接发生错误')
      }
    },

    changeBuju() {},

    changeBuju2() {}
  }
}
</script>

<style lang="scss" scoped>
.main_container {
  width: 100%;
  height: 100%;
  .block {
    background-color: #333333;
    border: 1px solid #ffffff;
  }
}
</style>
